package GameLogic

import (
	"PBMessage"

	"git.oschina.net/yangdao/extlib/math3d"

	"git.oschina.net/yangdao/extlib/data_type"

	"git.oschina.net/yangdao/SGLisp/parse"
	"git.oschina.net/yangdao/extlib"

	"git.oschina.net/yangdao/GameLib/Unit"
	"git.oschina.net/yangdao/SGLisp"
)

type Effect_LaunchUnit struct {
	*Unit.Effect
	launchUnitId int
	cacheArgs    []parse.Node
	Scene        *GameScene
	Mover        Unit.IMover
}

func CreateEffectLaunchUnit(args []parse.Node, context *SGLisp.Context) Unit.IEffect {
	newEffect := &Effect_LaunchUnit{
		Effect: &Unit.Effect{},
	}
	newEffect.cacheArgs = args
	return newEffect
}

func (this *Effect_LaunchUnit) OnLoad(srcAbility Unit.IAbility, srcUnit Unit.IUnit, otherArgs ...interface{}) {
	this.SrcUnit = srcUnit
	this.Scene = this.SrcUnit.Base().Scene.(*GameScene)
}

func (this *Effect_LaunchUnit) OnExec(context *SGLisp.Context) {
	this.launchUnitId = SGLisp.EvalNode(SGLisp.Evaluate(this.cacheArgs[1], context), context).(int)
	this.Mover = SGLisp.EvalNode(SGLisp.Evaluate(this.cacheArgs[2], context), context).(Unit.IMover)
	createOffset := SGLisp.EvalNode(SGLisp.Evaluate(this.cacheArgs[3], context), context).(data_type.IIndexed)

	newUnit := &GameUnit{UnitID: this.launchUnitId, Unit: &Unit.Unit{Scene: this.SrcUnit.Base().Scene}}
	newUnit.Init(extlib.Int64UUID(), false, this.SrcUnit.Base().Scene)
	newUnit.Load()
	newUnit.ParentUnit = this.SrcUnit
	offsetVec3 := &math3d.Vec3{X: createOffset.Nth(0).(float64), Y: createOffset.Nth(1).(float64), Z: createOffset.Nth(2).(float64)}
	newUnit.Unit.SetPos(*this.SrcUnit.Base().PosPtr().AddTo(offsetVec3))
	this.Scene.AddGameUnit(newUnit)
	newUnit.Unit.AddMover(this.Mover)

	this.Mover.Start(newUnit.Unit, func() {
		this.Scene.RemoveUnit(newUnit.Unit.GUID)
		//destoryUnit := &PBMessage.SC_UnitState{}
		//destoryUnit.State = proto.Int32(4)
		//destoryUnit.UnitId = proto.Int64(newUnit.Unit.GUID)
		//this.Scene.sendEachPlayer(PBMessage.PBID_SC_UnitState, destoryUnit)
	})
	createUnit := newUnit.toSCCreateUnit()
	this.Scene.sendEachPlayer(PBMessage.PBID_SC_CreateUnit, createUnit)

	addMover := lineMoverToPB(this.Mover.(*Unit.LineMover), newUnit.Unit)
	this.Scene.sendEachPlayer(PBMessage.PBID_SC_UnitAddMover, addMover)
}
